﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

namespace NJT.Services
{
    public static class 全局
    {
        public static IUnityContainer 人事部
        {
            get
            {
                return ServiceLocator.Current.GetInstance<IUnityContainer>();
            }
        }
        public static IEventAggregator 新闻部
        {
            get
            {
                return 人事部.Resolve<IEventAggregator>();
            }
        }
        /// <summary>
        /// 自动加载ViewModel,
        /// View路径为  ./Views/视图.
        /// ViewModel路径为  ./ViewModels/视图ViewModel.
        /// </summary>
        /// <param name="视图1"></param>
        /// <returns></returns>
        public static void 加载ViewModel(IView 视图1)
        {
            if (视图1 != null) ViewModelLocationProvider.AutoWireViewModelChanged(视图1);
        }

        /// <summary>
        /// SetDefaultViewModelFactory
        /// </summary>
        public static void Set默认解析器()
        {
            ViewModelLocationProvider.SetDefaultViewModelFactory(
                T => 人事部.Resolve(T)); ;
        }


        public static bool 激活视图(IRegion 区域1, string 视图名称)
        {
            var 视图1 = 区域1.GetView(视图名称);
            if (视图1 == null)
                return false;
            区域1.Activate(视图1);
            return true;
        }



        /// <summary>
        /// item1:返回 成功or失败
        /// item2:返回 错误消息.
        /// item3:返回 执行结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="func">The function.</param>
        /// <returns>Tuple&lt;System.Boolean, System.String, T&gt;.</returns>
        public static Tuple<bool, string, T> Try执行<T>(Func<T> func)
        {
            try
            {
                var r = func();
                return new Tuple<bool, string, T>(true, string.Empty, r);
            }
            catch (Exception ee)
            {
                return new Tuple<bool, string, T>(false, ee.Message, default(T));
            }
        }

        /// <summary>
        /// item1:返回 成功or失败
        /// item2:返回 错误消息.
        /// </summary>
        /// <param name="func">The function.</param>
        /// <returns>Tuple&lt;System.Boolean, System.String, T&gt;.</returns>
        public static Tuple<bool, string> Try执行(Action func)
        {
            try
            {
                func();
                return new Tuple<bool, string>(true, string.Empty);
            }
            catch (Exception ee)
            {
                return new Tuple<bool, string>(false, ee.Message);
            }
        }

    }
}
